<template>
  <el-form :model="formData" label-width="120px">
    <el-form-item label="品类名称">
      <el-input v-model="formData.name" />
    </el-form-item>
    <el-form-item label="图片">
      <Tuku v-model="formData.img"></Tuku>
    </el-form-item>
    <el-form-item label="父类">
      <el-tree-select
        v-model="formData.parentId"
        :data="data"
        :render-after-expand="false"
      />
    </el-form-item>
    <el-form-item label="排序">
      <el-input-number v-model="formData.sort" :min="1" :max="100" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="onSubmit">添加</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from "vue";
import Tuku from "@/components/Tuku.vue";
import { categoryApi } from "@/api";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();

//表单数据
const formData = reactive({
  name: "",
  img: "",
  sort: 0,
  parentId: "",
});
//父级分类数据
const data = ref([{ value: 0, label: "一级分类" }]);

//钩子函数
onMounted(() => {
  getCategoryList();
});

//查询分类列表
const getCategoryList = () => {
  categoryApi.select.call({ parentId: 0 }).then((res: any) => {
    res.forEach((item) => {
      item.value = item.id;
      item.label = item.name;
    });
    data.value = data.value.concat(res);
  });
};
//添加分类的api
const addCategory = () => {
  categoryApi.add.call(formData).then((res: any) => {
    ElMessage.success("添加成功");
  });
};
//提交表单
const onSubmit = () => {
  //调用接口添加品类
  addCategory();
  //跳转列表页面
  router.push({name:"category-list"})
};
</script>